import { ref, onMounted, onUnmounted, nextTick } from '@vue/composition-api'

/**
 * 动态计算容器高度
 * @param {Object} options 配置选项
 * @param {string} options.containerRef 容器元素的 ref
 * @param {string} options.subtractRef 需要减去高度的元素的 ref
 * @param {number} options.extraHeight 额外需要减去的高度（可选）
 * @returns {Object} 返回计算后的高度和更新函数
 */
export function useDynamicHeight(options) {
  const { containerRef, subtractRef, extraHeight = 0 } = options
  const dynamicHeight = ref(0)

  // 更新高度
  const updateHeight = () => {
    if (!containerRef.value || !subtractRef.value) return
    
    // 使用 getBoundingClientRect 获取更准确的高度
    const containerEl = containerRef.value.$el || containerRef.value
    const subtractEl = subtractRef.value.$el || subtractRef.value
    
    if (!containerEl || !subtractEl) return
    
    const containerHeight = containerEl.getBoundingClientRect().height
    const subtractHeight = subtractEl.getBoundingClientRect().height
    
    dynamicHeight.value = containerHeight - subtractHeight - extraHeight
  }

  // 监听窗口大小变化
  const handleResize = () => {
    nextTick(() => {
      updateHeight()
    })
  }

  onMounted(() => {
    // 等待 DOM 更新后再计算高度
    nextTick(() => {
      updateHeight()
    })
    window.addEventListener('resize', handleResize)
  })

  onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
  })

  return {
    dynamicHeight,
    updateHeight
  }
} 